package com.example.jobback.service.manager.impl;

import com.example.jobback.config.AuthConfig;
import com.example.jobback.mapper.ManagerMapper;
import com.example.jobback.po.Manager;
import com.example.jobback.po.User;
import com.example.jobback.req.common.password.ResetPasswordReq;
import com.example.jobback.req.common.phone.ResetPhoneReq;
import com.example.jobback.result.Result;
import com.example.jobback.service.common.UserCommonService;
import com.example.jobback.service.manager.ManagerAuthService;
import com.example.jobback.util.CACHEUtil;
import com.example.jobback.util.SecureEncryptionUtil;
import com.example.jobback.util.TLUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.example.jobback.util.RedisConstants.MANAGER_KEY;
import static com.example.jobback.util.RedisConstants.MANAGER_TTL;

/**
 * @ClassName: ManagerAuthServiceImpl
 * @Description:管理员-身份核验服务实现类
 * @Author: lhb
 * @Date: 2025/6/21
 */
@Service
public class ManagerAuthServiceImpl implements ManagerAuthService {

    private final UserCommonService userCommonService;

    private final AuthConfig authConfig;

    private final CACHEUtil cacheUtil;

    private final ManagerMapper managerMapper;

    public ManagerAuthServiceImpl(UserCommonService userCommonService, AuthConfig authConfig, ManagerMapper managerMapper, CACHEUtil cacheUtil) {
        this.userCommonService = userCommonService;
        this.authConfig = authConfig;
        this.managerMapper = managerMapper;
        this.cacheUtil = cacheUtil;
    }

    /**
     * @Description: 登录
     * @param phone
     * @param code
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 15:11
     */
    @Override
    public Result<Object> LoginByPhone(String phone, String code) {
        //验证码验证
        String phoneAes=null;
        try {
            if(!userCommonService.verifyCode(phone,code)) throw new IllegalArgumentException("VALIDATION_ERROR:验证码错误");
            //加密手机号码
            phoneAes= SecureEncryptionUtil.encrypt(phone,authConfig.getPhoneSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //查找该电话号码的三端记录
        User user=userCommonService.getUserByPhoneAes(phoneAes);
        if(user==null) throw new NullPointerException("无用户记录");
        Long userId = user.getUserId();
        Manager manager=managerMapper.getManagerByUserId(userId);
        if(manager == null) throw new NullPointerException("非管理员身份");
        BeanUtils.copyProperties(user, manager);
        //删除三端登录记录，只允许一端登录
        userCommonService.deleteAllLoginKeys(userId);
        //生成token，写入redis
        String token = userCommonService.setRedisUser(manager,manager.getUserId(),MANAGER_KEY,authConfig.getJwtManagerSecret(),MANAGER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("token生成失败");
        return Result.success(token);
    }

    /**
     * @Description: 退出登录
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 15:12
     */
    @Override
    public Result<Object> LoginOut() {
        Long userId= TLUtil.get(TLUtil.M).getUserId();
        String key=MANAGER_KEY+userId.toString();
        if (cacheUtil.deleteIfExists(key))return Result.success();
        throw new RuntimeException("登出失败");
    }

    /**
     * @Description: 重置登录
     * @param phone
     * @param password
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/23 11:57
     */
    @Override
    public Result<Object> login(String phone, String password) {
        String phoneAes= null;
        String passwordAes=null;
        //加密电话号码和密码
        try {
            phoneAes = SecureEncryptionUtil.encrypt(phone,authConfig.getPhoneSecret());
            passwordAes = SecureEncryptionUtil.encrypt(password,authConfig.getPasswordSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //查看用户记录
        User user=userCommonService.getUserByPhoneAes(phoneAes);
        if(user==null) throw new NullPointerException("无用户记录");
        Long userId = user.getUserId();
        //核验密码
        if(!userCommonService.authUserPassword(userId,passwordAes)){
            throw new IllegalArgumentException("VALIDATION_ERROR:用户名或者密码错误");
        }
        //查看是否是管理员身份
        Manager manager=managerMapper.getManagerByUserId(userId);
        if(manager == null) throw new NullPointerException("非管理员身份");
        BeanUtils.copyProperties(user, manager);
        //删除三端登录记录，只允许一端登录
        userCommonService.deleteAllLoginKeys(userId);
        //生成token，写入redis
        String token = userCommonService.setRedisUser(manager,manager.getUserId(),MANAGER_KEY,authConfig.getJwtManagerSecret(),MANAGER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("token生成失败");
        return Result.success(token);
    }

    /**
     * @Description: 修改密码
     * @param resetPasswordReq
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/25 17:20
     */
    @Override
    public Result<Object> resetPassword(ResetPasswordReq resetPasswordReq) {
        Manager manager = TLUtil.get(TLUtil.M);
        String phoneAes = manager.getPhoneAes();
        Long userId = manager.getUserId();
        return userCommonService.resetPassword(resetPasswordReq, phoneAes, userId);
    }

    /**
     * @Description: 更换手机号
     * @param resetPhoneReq
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/26 11:32
     */
    @Override
    public Result<Object> resetPhone(ResetPhoneReq resetPhoneReq) {
        Manager manager = TLUtil.get(TLUtil.M);
        String phoneAes = manager.getPhoneAes();
        Long userId = manager.getUserId();
        return userCommonService.resetPhone(resetPhoneReq, phoneAes, userId);
    }
}
